#################################################
# Results traditional analysis
#################################################

rm (list = ls())

library(lmtest)
library(sandwich)
library(stargazer)

# load function that does clustered SEs
vcovCluster <- function(
  model,
  cluster
)
{
  require(sandwich)
  require(lmtest)
  if(nrow(model.matrix(model))!=length(cluster)){
    stop("check your data: cluster variable has different N than model")
  }
  M <- length(unique(cluster))
  N <- length(cluster)           
  K <- model$rank   
  if(M<40){
    warning("Fewer than 40 clusters, variances may be unreliable")
  }
  dfc <- (M/(M - 1)) * ((N - 1)/(N - K))
  uj  <- apply(estfun(model), 2, function(x) tapply(x, cluster, sum));
  rcse.cov <- dfc * sandwich(model, meat = crossprod(uj)/N)
  return(rcse.cov)
}

#########################
# Load and explore data
#########################

# Generate log  
#sink("005_traditional_analysis.txt")

# Read data 
load("003_panel_brazil_traditional_2017jan11.RData")

##########################
# Regressions results
##########################

# All ego
mod1a = lm(outcome ~ t_ind_ego + v22c_presvote + v41e_thermserra_imp + v50_ideology_imp + as.factor(bairroibge), data = d_all_ego)
mod1a_c <- coeftest(mod1a, vcov = vcovCluster(mod1a, cluster = d_all_ego$bairroibge))

# All socio
mod1b = lm(outcome ~ t_ind_socio + v22c_presvote + v41e_thermserra_imp + v50_ideology_imp + as.factor(bairroibge), data = d_all_socio)
mod1b_c <- coeftest(mod1b, vcov = vcovCluster(mod1b, cluster = d_all_socio$bairroibge))

# TABLE 4 MANUSCRIPT 
stargazer(mod1a,mod1b,
          type = "text",
          title="Regression results traditional approach",
          align=TRUE, 
          omit.stat=c("LL","ser","f","rsq","adj.rsq"), 
          no.space=TRUE,  
          multicolumn = TRUE,
          table.placement = "H",
          #single.row = TRUE,
          #column.separate = c(4,4),
          covariate.labels=c("Egotropic perceptions","Sociotropic perceptions"),
          dep.var.caption  = "Voting for the incumbent",
          dep.var.labels.include = FALSE,
          omit = c("v22c_presvote","v41e_thermserra_imp","v50_ideology_imp","bairroibge","Constant"),
          add.lines = list(c("Controls","Yes","Yes"),
                           c("Neighborhood Fixed effects","Yes","Yes")))

#sink()
                           